﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using DomainDriver.DomainModeling.DataProviders;

namespace DomainDriver.DomainModeling.Queries
{
    public class AndQuery<T> : IQuery<T>
    {
        private IDataProvider m_DataProvider;
        private List<IQuery<T>> m_NestedQueries;

        public AndQuery()
        {
            m_NestedQueries = new List<IQuery<T>>();
        }

        public void AddNestedQuery(IQuery<T> query)
        {
            if (query == this)
            { throw new ApplicationException(); }
            if (m_NestedQueries.Contains(query))
            { throw new ApplicationException(); }
            m_NestedQueries.Add(query);
        }

        public Func<T, bool> GetQueryPredicate(IDataProvider dataProvider)
        {
            m_DataProvider = dataProvider;
            return CheckForAndQueryMatch;
        }

        protected bool CheckForAndQueryMatch(T valueToCheck)
        {
            foreach (IQuery<T> nestedQuery in m_NestedQueries)
            {
                Func<T, bool> predicate = nestedQuery.GetQueryPredicate(m_DataProvider);
                if (!predicate(valueToCheck))
                { return false; }
            }
            return true;
        }
    }
}